<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
date_default_timezone_set ( 'prc' );
require_once (dirname ( __FILE__ ) . "/../../PHPExcel/PHPExcel.php");
class Product extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		if (! $this->session->userdata ( 'logged_in' )) {
			redirect ( 'index_admin/login' );
			exit ();
		}
	}
	/*
	 * 返回商品列表
	 */
	public function index() {
    	$name = $this->uri->segment(4);
    	$name=urldecode($name);//转化为汉字
    	$ordertype = $this->uri->segment(6);
		$category = $this->uri->segment(8);
		$variety = $this->uri->segment(10);
		$sale = $this->uri->segment(12);
 		$purprice = $this->uri->segment(14);
		$type2 = $this->uri->segment(16);
 		$show = $this->uri->segment(18);
		
    	if(empty($name)){//这里是为了将name加到url上,虽然前台也有处理，但是也有没有参数进入该方法的时候
    		$name="empty";
    	}
    	if(empty($ordertype)){//默认根据上下架倒序排序
    		$ordertype=4;
    	}
    	if(empty($category)){
    		$category=0;
    	}
		if(empty($variety)){
    		$variety=0;
    	}
		if(empty($sale)){
    		$sale=0;
    	}
		if(empty($purprice)){
    		$purprice=0;
    	}
		if(empty($type2)){
    		$type2=0;
    	}
		if(empty($show)){
    		$show=0;
    	}
		$data ['ordertype']=$ordertype;
		$data ['categoryid']=$category;
		$data ['varietyid']=$variety;
		$data ['sale']=$sale;
		$data ['purprice']=$purprice;
		$data ['type']=$type2;
		$data ['show']=$show;
    	$this->load->library ( 'pagination' );
    	// 每页显示数据条数
    	$per_page=20;//每页显示20项
    	
    	$config['base_url']=site_url('product/index/name/'.$name.'/ordertype/'.$ordertype.'/category/'.$category.'/variety/'.$variety.'/sale/'.$sale.'/purprice/'.$purprice.'/type/'.$type2.'/show/'.$show);
    	$this->load->model ( 'product_model' );
    	
    	if($name=="empty"){//这里是为了搜索
    		$name=null;
    	}
    	// 数据总数
    	$config ['total_rows'] = $this->product_model->count_products($name,$category,$variety,$sale,$purprice,$type2,$show);
    	//$config ['total_rows']=200; //测试用，总行数太少，分页效果无法出现
    	$config ['per_page'] = $per_page;
    	$config ['first_link'] = '第一页';
    	$config ['last_link'] = '最后一页';
    	$config ['next_link'] = '下一页';
    	$config ['prev_link'] = '上一页';
    	$config['uri_segment'] =19;
    	//$config['num_links'] = 2;
    	 
    	$this->pagination->initialize($config);
    	//echo $this->pagination->create_links();
    	$data['links']=$this->pagination->create_links();
    	//偏移量
    	$offset=intval($this->uri->segment(19));
    	
    	if($ordertype==1){
    		$type="id";
    		$order="asc";
    	}else if($ordertype==2){
    		$type="id";
    		$order="desc";
    	}else if($ordertype==3){
    		$type="show";
    		$order="asc";
    	}else if($ordertype==4){
    		$type="show";
    		$order="desc";
    	}
    	$this->load->model ( 'product_model' );
    	$data ['products'] = $this->product_model->search_products_by_name_and_cat($per_page,$offset,$name,$type,$order,$category,$variety,$sale,$purprice,$type2,$show);
		$this->load->model ( 'category_model' );
		$data['categories']  = $this->category_model->find_all_categories();
    	$this->load->model ( 'variety_model' );
    	$data ['varieties'] = $this->variety_model->find_all_varieties ();
	
    	//$this->load->view ( 'product/pagination', $data );
    	$data ['title'] = '商品管理 - 集市宝仓库管理系统';
    	$this->load->view ( 'header', $data );
    	$this->load->view ( 'product/index' );
    	$this->load->view ( 'footer' );
	}
	/*
	 * 根据ID返回大小类信息(用于添加商品时的分类)
	 */
	public function getcategory() {
		$categoryid = $this->input->post ( 'categoryid' );
		$data=NULL;
		if(isset($categoryid)){
			if($categoryid=='0'){
				$this->load->model ( 'category_model' );
				$data = $this->category_model->find_all_categories();//这里直接是用$data的
			}else{
				$this->load->model ( 'variety_model' );
				$data = $this->variety_model->find_varieties_by_cat ( $categoryid );
			}	
		}
		return_json ( TRUE, $data, '查询成功！' );
	}
	/*
	 * 跳转到添加商品页面
	 */
	public function add() {
		$data ['title'] = '添加商品 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'product/add' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 跳转到编辑商品页面
	 */
	public function edit() {
		$id = $this->uri->segment(4);
		$this->load->model ( 'category_model' );
		$data ['categories'] = $this->category_model->find_all_categories ();
		$this->load->model ( 'variety_model' );
		$data ['varieties'] = $this->variety_model->find_all_varieties ();//编辑时返回所有小类去选择
		$this->load->model ( 'product_model' );
		$data ['product'] = $this->product_model->load ( $id );
		$data ['title'] = '编辑商品 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'product/edit' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 保存商品信息(不更新价格变化)
	 */
	public function save() {
		$id = $this->input->post('id');
		$newproduct = array (
				'categoryid' => $this->input->post ( 'categoryid' ),
				'varietyid' => $this->input->post ( 'varietyid' ),
				'name' => $this->input->post ( 'name' ),
				'image' => $this->input->post ( 'image' ),
				'description' => $this->input->post ( 'description' ),
				'position' => $this->input->post ( 'position' ),
				'purprice' => $this->input->post ( 'purprice' ),
				'price' => $this->input->post ( 'price' ),
				'unit' => $this->input->post ( 'unit' ) ,
				'stock' => $this->input->post ( 'stock' ),
				'sale' => $this->input->post ( 'sale' ),
				'type' => $this->input->post ( 'type' )  
		);
		$this->load->model ( 'product_model' );
		if ($id) {
			$product = $this->product_model->load ( $id );
			if($this->product_model->update ( $id, $newproduct )){
				if($product['price']!=$newproduct['price']){
					$adminid = $this->session->userdata ( 'id' );
					$pricechange = array (
							'productid' => $id,
							'oldprice' => $product['price'],
							'price' => $newproduct['price'],
							'adminid' => $adminid,
							'update_time' => date ( "Y-m-d H:i:s" )
					);
					$this->load->model ( 'pricechange_model' );
					$this->pricechange_model->create($pricechange);//没有进一步判断
				}
				if($product['purprice']!=$newproduct['purprice']){
					$adminid = $this->session->userdata ( 'id' );
					$purpricechange = array (
							'productid' => $id,
							'oldprice' => $product['purprice'],
							'purprice' => $newproduct['purprice'],
							'adminid' => $adminid,
							'update_time' => date ( "Y-m-d H:i:s" )
					);
					$this->load->model ( 'purpricechange_model' );
					$this->purpricechange_model->create($purpricechange);
				}
				return_json(TRUE,'','修改成功！'); 
			}else{
				return_json(FALSE,'','信息未改动！');
			}
		} else {
			$productid=$this->product_model->create ( $newproduct );
			if(!empty($productid)){
				return_json(TRUE,'','添加成功！');
			}else{
				return_json(FALSE,'','添加失败！');
			}
		}
	}
	/*
	 * 删除商品信息(暂时不用，通常用下架功能)
	 */
	public function delete() {
	    $id = $this->input->post('id');
		$this->load->model ( 'product_model' );
		if ($this->product_model->delete ( $id )) {//要不要考虑订单里有这个产品
			return_json(TRUE,'','删除成功！'); 
	    }else{
	    	return_json(FALSE,'','删除失败！');
	    }
    }
	/*
	 * 更新商品信息(主要是修改小类)
	 */
    public function update() {
    	$id = $this->input->post('id');
    	$varietyid = $this->input->post('varietyid');
    	$product = array (
    			'varietyid' => $varietyid
    	);
    	$this->load->model ( 'product_model' );
    	if($this->product_model->update ( $id, $product )){
    		return_json(TRUE,'','修改成功！');
    	}else{
    		return_json(FALSE,'','信息未改动！');
    	}
    }
  	/*
	 *上/下架商品
	 */
    public function setproductstate(){
    	$productid = $this->input->post ( 'productid' );
    	$state = $this->input->post ( 'state' );
    	$this->load->model ( 'product_model' );
		$product = $this->product_model->load ( $productid );
    	$newproduct = array (
    			'show' => $state
    	);
    	if ($this->product_model->update ( $productid, $newproduct )) {
    		$this->load->model ( 'shelve_model' );
    		if($state==0){//下架时记录
				$shelve = array (
					'productid' => $productid,
    				'name' => $product['name'],
    				'date' => date ( "Y-m-d H:i:s" ),
    				'state' => 0
    			);
				$this->load->model ( 'shoppingcart_model' );
				if(!empty($productid)){//下架时清空购物车中的该商品
					$this->shoppingcart_model->delete_by_product($productid); 
				}
			}else{//上架时记录
				$shelve = array (
					'productid' => $productid,
    				'name' => $product['name'],
    				'date' => date ( "Y-m-d H:i:s" ),
    				'state' => 1
    			);
			}
			$this->shelve_model->create ($shelve);
    		return_json ( TRUE, '', '操作成功！' );
    	}else{
    		return_json ( FALSE, '', '操作失败！' );
    	}
    }
	/*
	 *补货/供应功能
	 */
    public function setproductshort(){
    	$productid = $this->input->post ( 'productid' );
    	$short = $this->input->post ( 'short' );
    	$this->load->model ( 'product_model' );
    	$newproduct = array (
    			'short' => $short
    	);
    	if ($this->product_model->update ( $productid, $newproduct )) {
    		return_json ( TRUE, '', '操作成功！' );
    	}else{
    		return_json ( FALSE, '', '操作失败！' );
    	}
    }
	/*
	 *修改商品进货价
	 */ 
    public function setproductpurprice(){
    	$id = $this->input->post ( 'id' );
    	$productid = $this->input->post ( 'productid' );
    	$purprice = $this->input->post ( 'purprice' );
    	$this->load->model ( 'product_model' );
		$this->load->model ( 'purprice_model' );
		if(!empty($id)){//不为空说明是录入进货价
			$newpurprice = array (
    			'purprice' => $purprice
    		);
			$this->purprice_model->update ( $id,$newpurprice );
		}
		$product = $this->product_model->load ( $productid );
    	$newproduct = array (
    			'purprice' => $purprice
    	);
    	if ($this->product_model->update ( $productid, $newproduct )) {
    		$adminid = $this->session->userdata ( 'id' );
			$purpricechange = array (
					'productid' => $productid,
					'oldprice' => $product['purprice'],
					'purprice' => $purprice,
					'adminid' => $adminid,
					'update_time' => date ( "Y-m-d H:i:s" )
			);
			$this->load->model ( 'purpricechange_model' );
			$this->purpricechange_model->create($purpricechange);
    		return_json ( TRUE, '', '更新成功！' );
    	}else{
    		return_json ( FALSE, '', '价格未改动！' );
    	}
    }
	/*
	 *修改商品出售价(更新价格变化)
	 */ 
	public function setproductprice(){
    	$productid = $this->input->post ( 'productid' );
    	$price = $this->input->post ( 'price' );
    	$this->load->model ( 'product_model' );
		$product = $this->product_model->load ( $productid );
    	$newproduct = array (
    			'price' => $price
    	);
    	if ($this->product_model->update ( $productid, $newproduct )) {
    		$adminid = $this->session->userdata ( 'id' );
			$pricechange = array (
					'productid' => $productid,
					'oldprice' => $product['price'],
					'price' => $price,
					'adminid' => $adminid,
					'update_time' => date ( "Y-m-d H:i:s" )
			);
			$this->load->model ( 'pricechange_model' );
			$this->pricechange_model->create($pricechange);//没有进一步判断
			if($newproduct['price']>$product['price']){//新价格大于旧价格
					$state=1;
			}elseif($newproduct['price']<$product['price']){
					$state=-1;
			}
			$this->load->model ( 'pricestate_model' );
			$pricestate=$this->pricestate_model->find_by_product($productid);
			if(!empty($pricestate)){//已经存在该商品的价格变更记录
				$newpricestate = array (
					'state' => $state,
					'update_time' => date ( "Y-m-d H:i:s" )
				);
				$this->pricestate_model->update($pricestate['id'],$newpricestate);
			}else{
				$newpricestate = array (
					'productid' => $productid,
					'state' => $state,
					'update_time' => date ( "Y-m-d H:i:s" )
				);
				$this->pricestate_model->create($newpricestate);
			}
    		return_json ( TRUE, '', '更新成功！' );
    	}else{
    		return_json ( FALSE, '', '价格未改动！' );
    	}
    }
	/*
	 *修改商品起售数量
	 */ 
	public function setproductstart(){
    	$productid = $this->input->post ( 'productid' );
    	$start = $this->input->post ( 'start' );
    	$this->load->model ( 'product_model' );
    	$newproduct = array (
    			'start' => $start
    	);
    	if ($this->product_model->update ( $productid, $newproduct )) {
    		return_json ( TRUE, '', '更新成功！' );
    	}else{
    		return_json ( FALSE, '', '更新失败！' );
    	}
    }
	/*
	 *修改商品排序号
	 */ 
    public function setproductposition(){
    	$productid = $this->input->post ( 'productid' );
    	$position = $this->input->post ( 'position' );
    	$this->load->model ( 'product_model' );
    	$newproduct = array (
    			'position' => $position
    	);
    	if ($this->product_model->update ( $productid, $newproduct )) {
    		return_json ( TRUE, '', '更新成功！' );
    	}else{
    		return_json ( FALSE, '', '更新失败！' );
    	}
    }
	/*
	 *修改商品导出号
	 */ 
	public function setproductexport(){
    	$productid = $this->input->post ( 'productid' );
    	$export = $this->input->post ( 'export' );
    	$this->load->model ( 'product_model' );
    	$newproduct = array (
    			'export' => $export
    	);
    	if ($this->product_model->update ( $productid, $newproduct )) {
    		return_json ( TRUE, '', '更新成功！' );
    	}else{
    		return_json ( FALSE, '', '更新失败！' );
    	}
    }
	/*
	 *设置特惠商品(暂时没用)
	 */ 
     public function setproductdiscount(){
    	$productid = $this->input->post ( 'productid' );
		$discount= $this->input->post ( 'discount' );
    	$this->load->model ( 'product_model' );
    	$newproduct = array (
    			'discount' => $discount
    	);
    	if ($this->product_model->update ( $productid, $newproduct )) {
    		return_json ( TRUE, '', '操作成功！' );
    	}else{
    		return_json ( FALSE, '', '操作失败！' );
    	}
    }
	 /*
	 * 导出商品列表
	 */ 
    public function exportProductlist() {
    	$resultPHPExcel = new PHPExcel ();
    	$resultPHPExcel->getActiveSheet ()->setCellValue ( 'A1', '序号' );
    	$resultPHPExcel->getActiveSheet ()->setCellValue ( 'B1', '名称' );
    	$resultPHPExcel->getActiveSheet ()->setCellValue ( 'C1', '价格' );
    	$resultPHPExcel->getActiveSheet ()->getStyle('A1:C1')->getFont()->setBold(true);
    	$this->load->model ( 'product_model' );
    	$products = $this->product_model->find_products ();
		$i = 2;
		foreach ( $products as $product ) {
			$resultPHPExcel->getActiveSheet ()->setCellValue ( 'A' .$i, $i-1);
			if(empty($product['description'])){
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'B' .$i, $product ['name']);
			}else{
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'B' .$i, $product ['name'].'('.$product['description'].')' );
			}
			$resultPHPExcel->getActiveSheet ()->setCellValue ( 'C' .$i, $product ['price'].'元/'.$product ['unit'] );
			$i ++;
		}
    	//左对齐
    	$resultPHPExcel->getActiveSheet ()->getStyle ( 'A1:C' . $i )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_LEFT );
    	// 设置列宽
    	$resultPHPExcel->getActiveSheet ()->getColumnDimension ( 'A' )->setWidth ( 5 );
    	$resultPHPExcel->getActiveSheet ()->getColumnDimension ( 'B' )->setWidth ( 55 );
    	$resultPHPExcel->getActiveSheet ()->getColumnDimension ( 'C' )->setWidth ( 15 );
    	$outputFileName = '商品列表.xls';
    	$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
    	// ob_start(); ob_flush();
    	header ( "Content-Type: application/force-download" );
    	header ( "Content-Type: application/octet-stream" );
    	header ( "Content-Type: application/download" );
    	header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
    	header ( "Content-Transfer-Encoding: binary" );
    	header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
    	header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
    	header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
    	header ( "Pragma: no-cache" );
    	$xlsWriter->save ( "php://output" );
    }
	 /*
	 * 导出报价单(打印时页面缩放比例))
	 */ 
    public function exportQuotation() {
    	$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$objActSheet->getDefaultRowDimension()->setRowHeight(12.75);//设置默认行高
		$objActSheet->mergeCells('A1:F2');
		$objActSheet->setCellValue ( 'A1', '集市宝食材报价单' );
		$objActSheet->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER );//水平居中
		$objActSheet->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
		$objActSheet->getStyle('A1')->getFont()->setName('宋体');
		$objActSheet->getStyle('A1')->getFont()->setSize(20);
		$objActSheet->getStyle('A1')->getFont()->setBold(true);
		$objActSheet->setCellValue ( 'A3', date ( "Y-m-d"));
		$objActSheet->getStyle('A3')->getFont()->setName('Calibri');
		$objActSheet->getStyle('A3')->getFont()->setSize(10);
		$objActSheet->getStyle('A3')->getFont()->setBold(true);
    	$this->load->model ( 'product_model' );
    	$products = $this->product_model->find_products ();
		$i =4;//行数
		$j=1;//序号
		$x=4;
		$max=4;
		$firstproducts = array_slice($products,0,130-count($products));//获取前130的商品
		$objActSheet->setCellValue ( 'A' .$i, '序号' );
    	$objActSheet->setCellValue ('B'.$i, '名称' );
    	$objActSheet->setCellValue ('C' .$i, '价格' );
		$objActSheet->setCellValue ( 'D' .$i, '序号' );
    	$objActSheet->setCellValue ( 'E' .$i, '名称' );
    	$objActSheet->setCellValue ('F' .$i, '价格' );
		$objActSheet->getStyle('A'.$i.':F'.$i)->getFont()->setBold(true);
		$i++;
		foreach ( $firstproducts as $product ) {
			if($j<=65){//65个商品一列
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'A' .$i, $j);
				if(empty($product['description'])){
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'B' .$i, $product ['name']);
				}else{
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'B' .$i, $product ['name'].'('.$product['description'].')' );
				}
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'C' .$i, $product ['price'].'元/'.$product ['unit'] );
				if($j==65){
					$i=4;
				}
			}else{
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'D' .$i, $j);
				if(empty($product['description'])){
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'E' .$i, $product ['name']);
				}else{
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'E' .$i, $product ['name'].'('.$product['description'].')' );
				}
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'F' .$i, $product ['price'].'元/'.$product ['unit'] );
			}
			$i ++;
			$j++;
		}
		$otherproducts = array_slice($products,131);//获取131以后的商品
		foreach ( $otherproducts as $product ) {
			if(($j-130)%136==1){
			$objActSheet->setCellValue ( 'A' .$i, '序号' );
    		$objActSheet->setCellValue ('B'.$i, '名称' );
    		$objActSheet->setCellValue ('C' .$i, '价格' );
			$objActSheet->setCellValue ( 'D' .$i, '序号' );
    		$objActSheet->setCellValue ( 'E' .$i, '名称' );
    		$objActSheet->setCellValue ('F' .$i, '价格' );
			$objActSheet->getStyle('A'.$i.':F'.$i)->getFont()->setBold(true);
			$i++;
			$x=$i;//记住第二列的开始位置
			}
			if(floor(($j-130-1)/68)%2==0){
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'A' .$i, $j);
				if(empty($product['description'])){
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'B' .$i, $product ['name']);
				}else{
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'B' .$i, $product ['name'].'('.$product['description'].')' );
				}
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'C' .$i, $product ['price'].'元/'.$product ['unit'] );
				$i ++;
				if(floor(($j-130)/68)%2==1){
					$i=$x;
				}
			}else{
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'D' .$i, $j);
				if(empty($product['description'])){
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'E' .$i, $product ['name']);
				}else{
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'E' .$i, $product ['name'].'('.$product['description'].')' );
				}
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'F' .$i, $product ['price'].'元/'.$product ['unit'] );
				$i ++;
				if(floor(($j-130)/68)%2==0){
					$x=$i;
				}
			}
			if($i>$max){
				$max=$i;
			}
			$j++;
		}
			$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
		$objActSheet->getStyle('A4:F'.$max)->applyFromArray($styleArray);
		$objActSheet->getStyle('A4:F'.$max)->getFont()->setName('黑体');
		$objActSheet->getStyle('A4:F'.$max)->getFont()->setSize(11);
    	//左对齐
    	$resultPHPExcel->getActiveSheet ()->getStyle ( 'A4:F' . $max )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_LEFT );
    	// 设置列宽
    	$objActSheet->getColumnDimension ( 'A' )->setWidth ( 4.12);
    	$objActSheet->getColumnDimension ( 'B' )->setWidth ( 36.24);
    	$objActSheet->getColumnDimension ( 'C' )->setWidth ( 8.456 );
		$objActSheet->getColumnDimension ( 'D' )->setWidth ( 4.12 );
    	$objActSheet->getColumnDimension ( 'E' )->setWidth ( 36.24 );
    	$objActSheet->getColumnDimension ( 'F' )->setWidth ( 8.456  );
    	$outputFileName = '报价单.xls';
    	$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
    	// ob_start(); ob_flush();
    	header ( "Content-Type: application/force-download" );
    	header ( "Content-Type: application/octet-stream" );
    	header ( "Content-Type: application/download" );
    	header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
    	header ( "Content-Transfer-Encoding: binary" );
    	header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
    	header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
    	header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
    	header ( "Pragma: no-cache" );
    	$xlsWriter->save ( "php://output" );
    }
	 /*
	 * 导出进货价(仿照报价单)
	 */ 
    public function exportPurprice() {
    	$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$objActSheet->getDefaultRowDimension()->setRowHeight(12.75);//设置默认行高
		$objActSheet->mergeCells('A1:F2');
		$objActSheet->setCellValue ( 'A1', '集市宝食材进货价' );
		$objActSheet->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER );//水平居中
		$objActSheet->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
		$objActSheet->getStyle('A1')->getFont()->setName('宋体');
		$objActSheet->getStyle('A1')->getFont()->setSize(20);
		$objActSheet->getStyle('A1')->getFont()->setBold(true);
		$objActSheet->setCellValue ( 'A3', date ( "Y-m-d"));
		$objActSheet->getStyle('A3')->getFont()->setName('Calibri');
		$objActSheet->getStyle('A3')->getFont()->setSize(10);
		$objActSheet->getStyle('A3')->getFont()->setBold(true);
    	$this->load->model ( 'product_model' );
    	$products = $this->product_model->find_products ();
		$i =4;//行数
		$j=1;//序号
		$x=4;
		$max=4;
		$firstproducts = array_slice($products,0,130-count($products));
		$objActSheet->setCellValue ( 'A' .$i, '序号' );
    	$objActSheet->setCellValue ('B'.$i, '名称' );
    	$objActSheet->setCellValue ('C' .$i, '价格' );
		$objActSheet->setCellValue ( 'D' .$i, '序号' );
    	$objActSheet->setCellValue ( 'E' .$i, '名称' );
    	$objActSheet->setCellValue ('F' .$i, '价格' );
		$objActSheet->getStyle('A'.$i.':F'.$i)->getFont()->setBold(true);
		$i++;
		foreach ( $firstproducts as $product ) {
			if($j<=65){
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'A' .$i, $j);
				if(empty($product['description'])){
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'B' .$i, $product ['name']);
				}else{
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'B' .$i, $product ['name'].'('.$product['description'].')' );
				}
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'C' .$i, $product ['purprice'].'元/'.$product ['unit'] );
				if($j==65){
					$i=4;
				}
			}else{
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'D' .$i, $j);
				if(empty($product['description'])){
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'E' .$i, $product ['name']);
				}else{
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'E' .$i, $product ['name'].'('.$product['description'].')' );
				}
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'F' .$i, $product ['purprice'].'元/'.$product ['unit'] );
			}
			$i ++;
			$j++;
		}
		$otherproducts = array_slice($products,131);
		foreach ( $otherproducts as $product ) {
			if(($j-130)%136==1){
			$objActSheet->setCellValue ( 'A' .$i, '序号' );
    		$objActSheet->setCellValue ('B'.$i, '名称' );
    		$objActSheet->setCellValue ('C' .$i, '价格' );
			$objActSheet->setCellValue ( 'D' .$i, '序号' );
    		$objActSheet->setCellValue ( 'E' .$i, '名称' );
    		$objActSheet->setCellValue ('F' .$i, '价格' );
			$objActSheet->getStyle('A'.$i.':F'.$i)->getFont()->setBold(true);
			$i++;
			$x=$i;
			}
			if(floor(($j-130-1)/68)%2==0){
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'A' .$i, $j);
				if(empty($product['description'])){
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'B' .$i, $product ['name']);
				}else{
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'B' .$i, $product ['name'].'('.$product['description'].')' );
				}
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'C' .$i, $product ['purprice'].'元/'.$product ['unit'] );
				$i ++;
				if(floor(($j-130)/68)%2==1){
					$i=$x;
				}
			}else{
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'D' .$i, $j);
				if(empty($product['description'])){
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'E' .$i, $product ['name']);
				}else{
					$resultPHPExcel->getActiveSheet ()->setCellValue ( 'E' .$i, $product ['name'].'('.$product['description'].')' );
				}
				$resultPHPExcel->getActiveSheet ()->setCellValue ( 'F' .$i, $product ['purprice'].'元/'.$product ['unit'] );
				$i ++;
				if(floor(($j-130)/68)%2==0){
					$x=$i;
				}
			}
			if($i>$max){
				$max=$i;
			}
			$j++;
		}
			$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
		$objActSheet->getStyle('A4:F'.$max)->applyFromArray($styleArray);
		$objActSheet->getStyle('A4:F'.$max)->getFont()->setName('黑体');
		$objActSheet->getStyle('A4:F'.$max)->getFont()->setSize(11);
    	//左对齐
    	$resultPHPExcel->getActiveSheet ()->getStyle ( 'A4:F' . $max )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_LEFT );
    	// 设置列宽
    	$objActSheet->getColumnDimension ( 'A' )->setWidth ( 4.12);
    	$objActSheet->getColumnDimension ( 'B' )->setWidth ( 36.24);
    	$objActSheet->getColumnDimension ( 'C' )->setWidth ( 8.456 );
		$objActSheet->getColumnDimension ( 'D' )->setWidth ( 4.12 );
    	$objActSheet->getColumnDimension ( 'E' )->setWidth ( 36.24 );
    	$objActSheet->getColumnDimension ( 'F' )->setWidth ( 8.456  );
    	$outputFileName = '进货价.xls';
    	$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
    	// ob_start(); ob_flush();
    	header ( "Content-Type: application/force-download" );
    	header ( "Content-Type: application/octet-stream" );
    	header ( "Content-Type: application/download" );
    	header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
    	header ( "Content-Transfer-Encoding: binary" );
    	header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
    	header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
    	header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
    	header ( "Pragma: no-cache" );
    	$xlsWriter->save ( "php://output" );
    }
	/*
	 * 得到所有商品的信息(商品自动完成功能)
	 */
	 public function getProducts() {
    	$name = $this->input->post('name');
    	$this->load->model ( 'product_model' );
    	$data=$this->product_model->get_products_by_name ( $name );
    	return_json_data($data);
    }
	 /*
	 * 得到所有上架商品的信息(商品自动完成功能)
	 */
	 public function getShowProduct() {
    	$name = $this->input->post('name');
    	$this->load->model ( 'product_model' );
    	$datas=$this->product_model->get_show_product_by_name ( $name );
		$startdate = '2015-08-11';
		$enddate= date ( "Y-m-d" );
		$this->load->model ( 'cost_model' );
		$this->load->model ( 'orderdetail_model' );
		$this->load->model ( 'lost_model' );
		foreach($datas as $key=>$data){
    		$totalproduct = $this->cost_model->get_cost_by_date_product ($data['id'],$startdate,$enddate);
			$product = $this->orderdetail_model->get_orderdetail_by_date_product ($data['id'],$startdate,date ( "Y-m-d", strtotime ( "+1 day" )));
    		$lostproduct = $this->lost_model->get_lost_by_date_product ($data['id'],$startdate,$enddate);
			$stock=0;
			if(!empty($totalproduct)){
				if(!empty($product)){
					$totalproduct['amount']=$totalproduct['amount']-$product['amount'];
				}
				if(!empty($lostproduct)){
					$totalproduct['amount']=$totalproduct['amount']-$lostproduct['amount'];
				}
				$stock=$totalproduct['amount'];
			}
			$datas[$key]['stock']=strval($stock);
		}
    	return_json_data($datas);
    }
	 /*
	 * 得到所有上架商品的信息(商品自动完成功能，添加订单详情)
	 */
	 public function getShowProducts() {
    	$name = $this->input->post('name');
		$userid = $this->input->post('userid');
		$this->load->model ( 'user_model' );
		$user=$this->user_model->load($userid);
    	$this->load->model ( 'product_model' );
    	$data=$this->product_model->get_show_products_by_name ( $name,$user['type'] );
    	return_json_data($data);
    }
	 /*
	 * 查看价格变动
	 */
	public function pricechange() {
		$name = $this->uri->segment(4);
    	$name=urldecode($name);//转化为汉字
    	if(empty($name)){
    		$name="empty";
    	}
		
		$this->load->library ( 'pagination' );
		// 每页显示数据条数
		$per_page=20;//暂定为20条
		
		$config['base_url']=site_url('product/pricechange/name/'.$name);
		$this->load->model ( 'pricechange_model' );
		
		if($name=="empty"){//这里是为了搜索
    		$name=null;
    	}
		
		// 数据总数
		$config ['total_rows'] = $this->pricechange_model->count_pricechanges($name);
		$config ['per_page'] = $per_page;
		$config ['first_link'] = '第一页';
		$config ['last_link'] = '最后一页';
		$config ['next_link'] = '下一页';
		$config ['prev_link'] = '上一页';
		$config['uri_segment'] =5;
		
		$this->pagination->initialize($config);
		$data['links']=$this->pagination->create_links();
		//偏移量
		$offset=intval($this->uri->segment(5));
		$data ['pricechanges'] = $this->pricechange_model->find_all_pricechanges ($name,$per_page,$offset);
		$data ['title'] = '价格变动 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'product/pricechange' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 生成通知
	 */
	public function notice() {
		$this->load->model ( 'pricechange_model' );
		$pricechanges = $this->pricechange_model->find_pricechanges_by_date (date ( "Y-m-d" ));
		$notice="每日价格提示(".date ( "m.d" )."):";
		foreach($pricechanges as $pricechange){
			if($pricechange['price']>$pricechange['oldprice']){
				$notice=$notice.$pricechange['name']."↑".($pricechange['price']-$pricechange['oldprice'])."元,";
			}else{
				$notice=$notice.$pricechange['name']."↓".($pricechange['oldprice']-$pricechange['price'])."元,";
			}
		}
		$data ['notice'] =$notice;
		$data ['title'] = '生成通知 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'product/notice' );
		$this->load->view ( 'footer' );
	}
	 /*
	 * 查看下架商品
	 */
	public function shelves() {
		$show = $this->uri->segment(4);
		if(empty($show)){
			$show=0;
		}
		$this->load->library ( 'pagination' );
		// 每页显示数据条数
		$per_page=10;//暂定为10条
		
		$config['base_url']=site_url('product/shelves/show/'.$show);
		$this->load->model ( 'shelve_model' );
		// 数据总数
		$config ['total_rows'] = $this->shelve_model->count_shelves($show);
		$config ['per_page'] = $per_page;
		$config ['first_link'] = '第一页';
		$config ['last_link'] = '最后一页';
		$config ['next_link'] = '下一页';
		$config ['prev_link'] = '上一页';
		$config['uri_segment'] =5;
		
		$this->pagination->initialize($config);
		$data['links']=$this->pagination->create_links();
		//偏移量
		$offset=intval($this->uri->segment(5));
		$data ['shelves'] = $this->shelve_model->find_all_shelves ($show,$per_page,$offset);
		$data ['title'] = '下架商品 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'product/shelves' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 查看补货中商品
	 */
	public function shorts() {
		$this->load->library ( 'pagination' );
		// 每页显示数据条数
		$per_page=10;//暂定为10条
		
		$config['base_url']=site_url('product/shorts');
		$this->load->model ( 'product_model' );
		// 数据总数
		$config ['total_rows'] = $this->product_model->count_short_products();
		$config ['per_page'] = $per_page;
		$config ['first_link'] = '第一页';
		$config ['last_link'] = '最后一页';
		$config ['next_link'] = '下一页';
		$config ['prev_link'] = '上一页';
		$config['uri_segment'] =3;
		
		$this->pagination->initialize($config);
		$data['links']=$this->pagination->create_links();
		//偏移量
		$offset=intval($this->uri->segment(3));
		$data ['shorts'] = $this->product_model->find_short_products ($per_page,$offset);
		$data ['title'] = '查看补货中商品 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'product/shorts' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 查看库存(白天)
	 */
	public function getStocks() {
		$startdate = $this->uri->segment(4);
		$enddate = $this->uri->segment(6);
		$this->load->model ( 'cost_model' );
    	$totalproducts = $this->cost_model->get_products_by_date ($startdate,$enddate);
		$this->load->model ( 'orderdetail_model' );
		$products = $this->orderdetail_model->get_orderdetails_by_date ($startdate,$enddate);
		$this->load->model ( 'lost_model' );
    	$lostproducts = $this->lost_model->get_products_by_date ($startdate,$enddate);
		$this->load->model ( 'product_model' );
		$stockproducts=$this->product_model->find_stock_products();
		foreach($products as $product){//减去订单的商品
			foreach($totalproducts as  $key=>$totalproduct){
				if($product['productid']==$totalproduct['productid']){
					$totalproducts[$key]['amount']=$totalproduct['amount']-$product['amount'];
					break;
				}
			}
		}
		foreach($lostproducts as $product){//减去损耗的商品
			foreach($totalproducts as  $key=>$totalproduct){
				if($product['productid']==$totalproduct['productid']){
					$totalproducts[$key]['amount']=$totalproduct['amount']-$product['amount'];
					break;
				}
			}
		}
		foreach($stockproducts as $key=>$stockproduct){
			$weeklyresult= $this->orderdetail_model->get_weeklyamount_by_product ($stockproduct['id']);//线上周销售量
			$monthlyresult= $this->orderdetail_model->get_monthlyamount_by_product ($stockproduct['id']);//线上月销售量
			$weeklyresult2= $this->lost_model->get_weeklyamount_by_product ($stockproduct['id']);//线下周销售量
			$monthlyresult2= $this->lost_model->get_monthlyamount_by_product ($stockproduct['id']);//线下月销售量
			$stockproducts[$key]['amount']="-";
			$stockproducts[$key]['weeklyamount']=$weeklyresult['amount']+$weeklyresult2['amount'];
			$stockproducts[$key]['monthlyamount']=$monthlyresult['amount']+$monthlyresult2['amount'];
			foreach($totalproducts as $product){
				if($stockproduct['id']==$product['productid']){
						$stockproducts[$key]['amount']=$product['amount'];
				}
			}
		}
		usort($stockproducts, function($a, $b) {
		if($a['amount']==$b['amount']){
			return 0;
		} else {
			return ($a['amount']>$b['amount']) ?1:-1;
		}
		});
		$data ['products'] = $stockproducts;
		$data ['startdate'] = $startdate;
		$data ['enddate'] = $enddate;
		$data ['title'] = '查看库存 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'product/stocks' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 查看库存(晚上)
	 */
	public function getNewStocks() {
		$startdate = $this->uri->segment(4);
		$enddate = $this->uri->segment(6);
		$this->load->model ( 'cost_model' );
    	$totalproducts = $this->cost_model->get_products_by_date ($startdate,$enddate);
		$this->load->model ( 'orderdetail_model' );
		$products = $this->orderdetail_model->get_orderdetails_by_date ($startdate,date ( "Y-m-d", strtotime ( "$enddate +1 day" )));
		$this->load->model ( 'lost_model' );
    	$lostproducts = $this->lost_model->get_products_by_date ($startdate,$enddate);
		$this->load->model ( 'product_model' );
		$stockproducts=$this->product_model->find_stock_products();
		foreach($products as $product){//减去订单的商品
			foreach($totalproducts as  $key=>$totalproduct){
				if($product['productid']==$totalproduct['productid']){
					$totalproducts[$key]['amount']=$totalproduct['amount']-$product['amount'];
					break;
				}
			}
		}
		foreach($lostproducts as $product){//减去损耗的商品
			foreach($totalproducts as  $key=>$totalproduct){
				if($product['productid']==$totalproduct['productid']){
					$totalproducts[$key]['amount']=$totalproduct['amount']-$product['amount'];
					break;
				}
			}
		}
		foreach($stockproducts as $key=>$stockproduct){
			$weeklyresult= $this->orderdetail_model->get_weeklyamount_by_product ($stockproduct['id']);//线上周销售量
			$monthlyresult= $this->orderdetail_model->get_monthlyamount_by_product ($stockproduct['id']);//线上月销售量
			$weeklyresult2= $this->lost_model->get_weeklyamount_by_product ($stockproduct['id']);//线下周销售量
			$monthlyresult2= $this->lost_model->get_monthlyamount_by_product ($stockproduct['id']);//线下月销售量
			$stockproducts[$key]['amount']="-";
			$stockproducts[$key]['weeklyamount']=$weeklyresult['amount']+$weeklyresult2['amount'];
			$stockproducts[$key]['monthlyamount']=$monthlyresult['amount']+$monthlyresult2['amount'];
			foreach($totalproducts as $product){
				if($stockproduct['id']==$product['productid']){
						$stockproducts[$key]['amount']=$product['amount'];
				}
			}
		}
		usort($stockproducts, function($a, $b) {
		if($a['amount']==$b['amount']){
			return 0;
		} else {
			return ($a['amount']>$b['amount']) ?1:-1;
		}
		});
		$data ['products'] = $stockproducts;
		$data ['startdate'] = $startdate;
		$data ['enddate'] = $enddate;
		$data ['title'] = '查看库存 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'product/stocks' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 查看库存(商品字段中的库存)
	 */
	public function getProductStocks() {
		$this->load->model ( 'product_model' );
		$this->load->model ( 'orderdetail_model' );
		$this->load->model ( 'lost_model' );
		$stockproducts=$this->product_model->find_all_stock_products();
		/*为了速度先注释掉
		foreach($stockproducts as $key=>$stockproduct){
			$weeklyresult= $this->orderdetail_model->get_weeklyamount_by_product ($stockproduct['id']);//线上周销售量
			//$monthlyresult= $this->orderdetail_model->get_monthlyamount_by_product ($stockproduct['id']);//线上月销售量
			$weeklyresult2= $this->lost_model->get_weeklyamount_by_product ($stockproduct['id']);//线下周销售量
			//$monthlyresult2= $this->lost_model->get_monthlyamount_by_product ($stockproduct['id']);//线下月销售量
			$stockproducts[$key]['weeklyamount']=$weeklyresult['amount']+$weeklyresult2['amount'];
			//$stockproducts[$key]['monthlyamount']=$monthlyresult['amount']+$monthlyresult2['amount'];
		}*/
		$data ['products'] = $stockproducts;
		$data ['title'] = '查看库存 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'product/newstocks' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 返回拆分商品列表
	 */
	public function dividelist() {
		$this->load->library ( 'pagination' );
		// 每页显示数据条数
		$per_page=20;//暂定为20条
		
		$config['base_url']=site_url('product/dividelist');
		$this->load->model ( 'divide_model' );
		// 数据总数
		$config ['total_rows'] = $this->divide_model->count_divides();
		$config ['per_page'] = $per_page;
		$config ['first_link'] = '第一页';
		$config ['last_link'] = '最后一页';
		$config ['next_link'] = '下一页';
		$config ['prev_link'] = '上一页';
		$config['uri_segment'] =3;
		
		$this->pagination->initialize($config);
		$data['links']=$this->pagination->create_links();
		//偏移量
		$offset=intval($this->uri->segment(3));
		$data ['divides'] = $this->divide_model->find_all_divides ($per_page,$offset);
		$data ['title'] = '拆分商品列表 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'product/dividelist' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 返回添加拆分商品页面
	 */
	public function adddivide() {
		$data ['title'] = '添加拆分商品 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'product/adddivide' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 返回编辑拆分商品页面
	 */
	public function editdivide() {
		$id = $this->uri->segment(4);
		$this->load->model ( 'divide_model' );
		$data ['divide'] = $this->divide_model->load ( $id );
		$data ['title'] = '编辑拆分商品 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'product/editdivide' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 保存拆分商品信息
	 */
	public function savedivide() {
		$id = $this->input->post('id');
		$name1 = $this->input->post('name1');
		$content1=explode('-',$name1);
		$productid1=$content1[1];
		$name2 = $this->input->post('name2');
		$content2=explode('-',$name2);
		$productid2=$content2[1];
		$amount = $this->input->post('amount');
	
		$divide = array (
			    'productid' => $productid1,
				'newproductid' => $productid2,
				'amount' => $amount,
		);
		$this->load->model ( 'divide_model' );
		if ($id) {
			if($this->divide_model->update ( $id,$divide )){
				return_json(TRUE,'','修改成功！'); 
			}else{
				return_json(FALSE,'','信息未改动！'); 
			}
		}else{
			$divideid=$this->divide_model->create ( $divide );
			if(!empty($divideid)){
				$this->load->model ( 'product_model' );
				$product = array (
			   	 	'divide' => 1
				);
				$this->product_model->update ( $productid1,$product );
				$this->product_model->update ( $productid2,$product );
				return_json(TRUE,'','添加成功！'); 
			}else{
				return_json(FALSE,'','添加失败！');
			}
		}
	}
	/*
	 * 删除拆分商品信息
	 */
	public function deletedivide() {
	    $id = $this->input->post('id');
		$this->load->model ( 'divide_model' );
		if ($this->divide_model->delete ( $id )) {
			return_json(TRUE,'','删除成功！'); 
	    }else{
	    	return_json(FALSE,'','删除失败！');
	    }
    }
	/*
	 * 导出库存(没有按照库存量排序)
	 */
	public function exportStocks() {
		$startdate = $this->uri->segment(4);
		$enddate = $this->uri->segment(6);
		$this->load->model ( 'cost_model' );
    	$totalproducts = $this->cost_model->get_products_by_date ($startdate,$enddate);
		$this->load->model ( 'orderdetail_model' );
		$products = $this->orderdetail_model->get_orderdetails_by_date ($startdate,$enddate);
		$this->load->model ( 'lost_model' );
    	$lostproducts = $this->lost_model->get_products_by_date ($startdate,$enddate);
		$this->load->model ( 'product_model' );
		$stockproducts=$this->product_model->find_stock_products();
		foreach($products as $product){//减去订单的商品
			foreach($totalproducts as  $key=>$totalproduct){
				if($product['productid']==$totalproduct['productid']){
					$totalproducts[$key]['amount']=$totalproduct['amount']-$product['amount'];
					break;
				}
			}
		}
		foreach($lostproducts as $product){//减去损耗的商品
			foreach($totalproducts as  $key=>$totalproduct){
				if($product['productid']==$totalproduct['productid']){
					$totalproducts[$key]['amount']=$totalproduct['amount']-$product['amount'];
					break;
				}
			}
		}
		foreach($stockproducts as $key=>$stockproduct){
			$weeklyresult= $this->orderdetail_model->get_weeklyamount_by_product ($stockproduct['id']);//线上周销售量
			$monthlyresult= $this->orderdetail_model->get_monthlyamount_by_product ($stockproduct['id']);//线上月销售量
			$weeklyresult2= $this->lost_model->get_weeklyamount_by_product ($stockproduct['id']);//线下周销售量
			$monthlyresult2= $this->lost_model->get_monthlyamount_by_product ($stockproduct['id']);//线下月销售量
			$stockproducts[$key]['amount']="-";
			$stockproducts[$key]['weeklyamount']=$weeklyresult['amount']+$weeklyresult2['amount'];
			$stockproducts[$key]['monthlyamount']=$monthlyresult['amount']+$monthlyresult2['amount'];
			foreach($totalproducts as $product){
				if($stockproduct['id']==$product['productid']){
						$stockproducts[$key]['amount']=$product['amount'];
				}
			}
		}
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$objActSheet->setCellValue ( 'A1', '商品名称' );
		$objActSheet->setCellValue ( 'B1', '库存量' );
		$objActSheet->setCellValue ( 'C1', '单位' );
		$objActSheet->setCellValue ( 'D1', '成本价' );
		$objActSheet->setCellValue ( 'E1', '总价' );
		$objActSheet->setCellValue ( 'F1', '周销售量' );
		$objActSheet->setCellValue ( 'G1', '月销售量' );
		$i=2;
		foreach($stockproducts as $stockproduct){
			$objActSheet->setCellValue ( 'A'.$i,  $stockproduct['name'].'-'.$stockproduct['description']);
			$objActSheet->setCellValue ( 'B'.$i,  $stockproduct['amount']);
			$objActSheet->setCellValue ( 'C'.$i,  $stockproduct['unit']);
			$objActSheet->setCellValue ( 'D'.$i,  $stockproduct['purprice']);	
			$objActSheet->setCellValue ( 'E'.$i,  $stockproduct['purprice']*$stockproduct['amount']);	
			$objActSheet->setCellValue ( 'F'.$i,  $stockproduct['weeklyamount']);
			$objActSheet->setCellValue ( 'G'.$i,  $stockproduct['monthlyamount']);
			$i++;
		}
		$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
		$objActSheet->getStyle('A1:G'.($i-1))->applyFromArray($styleArray);
		// 设置列宽
		$objActSheet->getColumnDimension ( 'A' )->setWidth ( 45 );
		$objActSheet->getColumnDimension ( 'B' )->setWidth ( 10 );
		$objActSheet->getColumnDimension ( 'C' )->setWidth ( 10 );
		$objActSheet->getColumnDimension ( 'D' )->setWidth ( 10 );
		$objActSheet->getColumnDimension ( 'E' )->setWidth ( 10 );
		$objActSheet->getColumnDimension ( 'F' )->setWidth ( 10 );
		$objActSheet->getColumnDimension ( 'G' )->setWidth ( 10 );	
		$outputFileName = '库存表.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 同步所有库存
	 */
	public function SynStocks() {
		$startdate = $this->input->post ( 'startdate' );
		$enddate= $this->input->post ( 'enddate' );
		$this->load->model ( 'cost_model' );
    	$totalproducts = $this->cost_model->get_products_by_date ($startdate,$enddate);
		$this->load->model ( 'orderdetail_model' );
		$products = $this->orderdetail_model->get_orderdetails_by_date ($startdate,date ( "Y-m-d", strtotime ( "$enddate +1 day" )));
		$this->load->model ( 'lost_model' );
    	$lostproducts = $this->lost_model->get_products_by_date ($startdate,$enddate);
		$this->load->model ( 'product_model' );
		$stockproducts=$this->product_model->find_stock_products();
		foreach($products as $product){
			foreach($totalproducts as  $key=>$totalproduct){
				if($product['productid']==$totalproduct['productid']){
					$totalproducts[$key]['amount']=$totalproduct['amount']-$product['amount'];
					break;
				}
			}
		}
		foreach($lostproducts as $product){//减去损耗的商品
			foreach($totalproducts as  $key=>$totalproduct){
				if($product['productid']==$totalproduct['productid']){
					$totalproducts[$key]['amount']=$totalproduct['amount']-$product['amount'];
					break;
				}
			}
		}
		foreach($stockproducts as $key=>$stockproduct){
			$stockproducts[$key]['amount']=0;
			foreach($totalproducts as $product){
				if($stockproduct['id']==$product['productid']){
						$stockproducts[$key]['amount']=$product['amount'];
				}
			}
		}
		foreach($stockproducts as $stockproduct){
			$product = array (
			   	'isstock' => 1,
				'stock' =>  $stockproduct['amount']
			);
			$this->product_model->update ($stockproduct['id'],$product );//同步失败暂时没有
		}
		return_json(TRUE,'','同步成功！'); 
	}
	/*
	 * 同步单个库存
	 */
	public function SynStock() {
		$productid=$this->input->post('productid');
		if(empty($productid)){
			return_json(FALSE,'','商品ID不能为空！');
		}
		$startdate = '2015-08-11';
		$enddate= date ( "Y-m-d" );
		$this->load->model ( 'cost_model' );
    	$totalproduct = $this->cost_model->get_cost_by_date_product ($productid,$startdate,$enddate);
		$this->load->model ( 'orderdetail_model' );
		$product = $this->orderdetail_model->get_orderdetail_by_date_product ($productid,$startdate,date ( "Y-m-d", strtotime ( "+1 day" )));
		$this->load->model ( 'lost_model' );
    	$lostproduct = $this->lost_model->get_lost_by_date_product ($productid,$startdate,$enddate);
		$stock=0;
		if(!empty($totalproduct)){
			if(!empty($product)){
				$totalproduct['amount']=$totalproduct['amount']-$product['amount'];
			}
			if(!empty($lostproduct)){
				$totalproduct['amount']=$totalproduct['amount']-$lostproduct['amount'];
			}
			$stock=$totalproduct['amount'];
		}
		$product = array (
				'stock' => $stock
		);
		$this->load->model ( 'product_model' );
		if($this->product_model->update ( $productid, $product)){
			return_json(TRUE,'','同步成功！'); 
		}else{
			return_json(FALSE,'','同步成功！');
		}
	}
	/*
	 * 全部推送到进货单
	 */
	public function exportSupplys() {
		$startdate = $this->input->post ( 'startdate' );
		$enddate= $this->input->post ( 'enddate' );
		$this->load->model ( 'cost_model' );
    	$totalproducts = $this->cost_model->get_products_by_date ($startdate,$enddate);
		$this->load->model ( 'orderdetail_model' );
		$products = $this->orderdetail_model->get_orderdetails_by_date ($startdate,$enddate);
		$this->load->model ( 'lost_model' );
    	$lostproducts = $this->lost_model->get_products_by_date ($startdate,$enddate);
		$this->load->model ( 'product_model' );
		$stockproducts=$this->product_model->find_stock_products();
		foreach($products as $product){
			foreach($totalproducts as  $key=>$totalproduct){
				if($product['productid']==$totalproduct['productid']){
					$totalproducts[$key]['amount']=$totalproduct['amount']-$product['amount'];
					break;
				}
			}
		}
		foreach($lostproducts as $product){//减去损耗的商品
			foreach($totalproducts as  $key=>$totalproduct){
				if($product['productid']==$totalproduct['productid']){
					$totalproducts[$key]['amount']=$totalproduct['amount']-$product['amount'];
					break;
				}
			}
		}
		foreach($stockproducts as $key=>$stockproduct){
			$stockproducts[$key]['amount']=0;
			foreach($totalproducts as $product){
				if($stockproduct['id']==$product['productid']){
						$stockproducts[$key]['amount']=$product['amount'];
				}
			}
		}
		$this->load->model ( 'supply_model' );
		foreach($stockproducts as $stockproduct){
			if($stockproduct['amount']<=0){
				$supply = array (
			   		'productid' => $stockproduct['id'],
					'name' =>  $stockproduct['name'],
					'price' => $stockproduct['purprice'], 
					'amount' => 1,
					'unit' => $stockproduct['unit'], 
					'total' => $stockproduct['purprice'],
					'supply_time' => date ( "Y-m-d"),
					'note' => '', 
				);
				$supplyid=$this->supply_model->create ( $supply );
				if(empty($supplyid)){
					return_json(TRUE,'','推送失败！'); 
				}
			}
		}
		return_json(TRUE,'','推送成功！'); 
	}
	/*
	 * 单个推送到进货单
	 */
	public function exportSupply() {
		$productid = $this->input->post('productid');
		$amount = $this->input->post('amount');
		$this->load->model ( 'product_model' );
		$product=$this->product_model->load($productid);
		$this->load->model ( 'supply_model' );
		$supply = array (
			'productid' => $product['id'],
			'name' =>  $product['name'],
			'price' => $product['purprice'], 
			'amount' => $amount,
			'unit' => $product['unit'], 
			'total' => $amount*$product['purprice'],
			'supply_time' => date ( "Y-m-d"),
			'note' => '', 
		);
		$supplyid=$this->supply_model->create ( $supply );
		if(!empty($supplyid)){
			return_json(TRUE,'','推送成功！'); 
		}else{
			return_json(TRUE,'','推送失败！'); 
		}
	}
	/*
	 * 跳转到进货价变化页面
	 */
	public function purpricechange() {
		$id = $this->uri->segment(4);
		$this->load->model ( 'product_model' );
		$data ['product'] = $this->product_model->load ( $id );
		$data ['title'] = '进货价变化 - 集市宝后台管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'product/purpricechange' );
		$this->load->view ( 'footer' );
	}
	 /*
	 * 根据商品ID和起始日期返回商品的价格变化信息
	 */
	 public function getPricechanges() {
	 	$productid = $this->input->post('productid');
	 	$startdate = $this->input->post ( 'startdate' );
		$enddate = $this->input->post ( 'enddate' );
		$startdate=date ( "Y-m-d", strtotime($startdate));
		$enddate=date ( "Y-m-d", strtotime($enddate));
    	$this->load->model ( 'purpricechange_model' );
    	$pricechanges=$this->purpricechange_model->get_by_product_date( $productid,$startdate,$enddate );
    	$dates=array();
		$prices=array();
		foreach($pricechanges as $pricechange){
			$dates[]=date ( "Y-m-d", strtotime($pricechange['update_time'])) ;
			$prices[]=doubleval($pricechange['purprice']) ;
		}
		$data['dates']=$dates;
		$data['prices']=$prices;
		return_json_data($data);
	 }
}